package com.iyao_app.im.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.iyao_app.R;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.UploadImage;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.http.RequestUrl;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.PickImageLoader;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.ToastUtil;
import com.iyao_app.view.LetterSpacingTextView;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.Luban;

public class FeedbackActivity extends BaseActivityWithHead {

    @BindView(R.id.et_number)
    EditText mEtNumber;
    @BindView(R.id.et_text)
    EditText mEtText;
    @BindView(R.id.rl_tu)
    SimpleDraweeView mRlTu;
    @BindView(R.id.tv_login)
    LetterSpacingTextView mTvLogin;
    @BindView(R.id.gone)
    ImageView mGone;

    private String headImage = null;
    final int IMAGE_PICKER = 1;

    private String number;
    private String text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        ButterKnife.bind(this);
        initPicker();
        initData();
        initView();
    }

    private void initView() {

    }

    private void initData() {
        setTitleTV(ResourcesUtils.getString(R.string.feedback));
    }

    @OnClick({R.id.rl_tu, R.id.tv_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_tu:
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.tv_login:
                comment();
                break;
        }
    }

    /**
     * 点击提交的时候
     */
    private void comment() {
        number = mEtNumber.getText().toString();
        text = mEtText.getText().toString().trim();
        if (number.equals("")){
            ToastUtil.showToast(this,"请填写手机号或者邮箱地址");
        }else {
            ToastUtil.showToast(this,"反馈成功");
            upLoadImage();
            finish();
        }
    }

    /**
     * 初始化图库
     */
    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);
        imagePicker.setSaveRectangle(false); //是否按矩形区域保存
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                ImageItem imageItem = images.get(0);
                mRlTu.setImageURI(ImageUtils.IMAGE_FILE + imageItem.path);
                mGone.setVisibility(View.GONE);
                headImage = imageItem.path;

            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void upLoadImage() {
        Flowable.just(headImage)
                .observeOn(Schedulers.io())
                .map(new Function<String, File>() {
                    @Override
                    public File apply(String s) throws Exception {
                        return Luban.with(FeedbackActivity.this).load(s).get().get(0);
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        int[] imageInfo = ImageUtils.getImageWidthHeight(file);
                        LogUtil.e(imageInfo[0] + "=====" + imageInfo[1]);
                        final HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("file", file);
                        NetUtils.getInstance().uploadImage(RequestUrl.UPLOAD_FILE, imageInfo[0], imageInfo[1], hashMap, new NetCallBack() {
                            @Override
                            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                                if (code == Contants.SUCCESS_CODE) {

                                    UploadImage uploadImage = model.getModel();
                                    if (uploadImage != null && !TextUtils.isEmpty(uploadImage.getFileUrl())) {
                                        complete(uploadImage.getFileUrl());
                                    }else if (uploadImage == null){
                                        LogUtil.e("xue","反馈成功");
                                        finish();
                                    }
                                } else {
                                    if (!TextUtils.isEmpty(message)) {
                                        Animation shake = AnimationUtils.loadAnimation(FeedbackActivity.this, R.anim.shake);
                                    }
                                }
                            }

                            @Override
                            public void onFail(String message, int code) {
                                Toast.makeText(FeedbackActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
                            }
                        }, UploadImage.class);
                    }
                });

    }
//
    public void complete(String fileUrl) {
        NetUtils.getInstance().userAppFeedback(number, DbUtil.getUser().id,text,fileUrl,new NetCallBack() {
            @Override
            public void onSuccess(final String message, final int code, String response, final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        LogUtil.e("xue","反馈成功");
                        finish();
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }
}